package com.ccp.dev.system.service;


import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.basic.consts.SystemConst;
import com.ccp.dev.system.dao.SysDataSourceDefDao;
import com.ccp.dev.system.model.SysDataSourceDef;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * SYS_DATA_SOURCE_DEF service类
 *
 * @author caishaofan
 */
@Service
public class SysDataSourceDefService extends BaseService<SysDataSourceDef> {

    @Resource
    private SysDataSourceDefDao sysDataSourceDefDao;

    /**
     * 添加或更新数据源模板
     *
     * @param sysDataSourceDef 数据源模板对象
     */
    @Transactional(rollbackFor = Exception.class)
    public int addOrUpdate(SysDataSourceDef sysDataSourceDef) {
        int count;
        sysDataSourceDef.setSettingJson(StringEscapeUtils.unescapeHtml4(sysDataSourceDef.getSettingJson()));
        try {
            if (StringUtil.isEmpty(sysDataSourceDef.getId())) {
                sysDataSourceDef.setId(UUIDUtils.getUUIDFor32());
                count = sysDataSourceDefDao.add(sysDataSourceDef);
            } else {
                count = sysDataSourceDefDao.update(sysDataSourceDef);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return count;
    }

    /**
     * 获取类中属性信息
     *
     * @param classPath 类路径
     * @return JSONArray
     */
    public JSONArray getHasSetterFieldsJsonArray(String classPath) {
        JSONArray jsonArray = new JSONArray();
        for (Field field : getHasSetterFields(classPath)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("name", field.getName());
            jsonObject.accumulate("comment", field.getName());
            jsonObject.accumulate("type", field.getType().getName());
            jsonObject.accumulate("baseAttr", SystemConst.DEFAULT_STR_ZERO);
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    /**
     * 获取类名为classPath的所有有setting的字段
     *
     * @param classPath 类路径
     * @return 属性集合
     */
    private List<Field> getHasSetterFields(String classPath) {
        List<Field> fields = new ArrayList<>();

        try {
            Class<?> classObj = Class.forName(classPath);
            for (Field field : classObj.getDeclaredFields()) {

                if (checkHasSetter(classObj, field)) {
                    fields.add(field);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fields;
    }

    /**
     * 检查字段在_class类中是否有setter
     *
     * @param classObj 类
     * @param field    属性
     * @return 布尔值
     */
    private boolean checkHasSetter(Class<?> classObj, Field field) {
        boolean b = false;

        for (Method method : classObj.getMethods()) {
            if (!method.getName().startsWith("set")) {
                continue;
            }
            if (method.getName().replace("set", "").equalsIgnoreCase(field.getName())) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 删除SYS_DATA_SOURCE_DEF
     *
     * @param id 数据源id
     * @return 删除的条数
     */
    @Transactional(rollbackFor = Exception.class)
    public int delDataSourceDefById(String id) {
        return sysDataSourceDefDao.delById(id);
    }

    /**
     * 查询去掉一个特定SYS_DATA_SOURCE_DEF的集合
     *
     * @param id 数据源模板id
     * @return List<SysDataSourceDef>
     */
    public List<SysDataSourceDef> queryListRemoveOneId(String id) {
        List<SysDataSourceDef> list = sysDataSourceDefDao.queryListRemoveOneId(id);
        return list;
    }
}
